package cn.lxb.web.starter.template.autoconfigure.config;

import cn.lxb.web.starter.template.autoconfigure.converter.LocalDateConverter;
import cn.lxb.web.starter.template.autoconfigure.converter.LocalDateTimeConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import javax.annotation.PostConstruct;


/**
 * 转换器配置
 *
 * @author 54lxb
 * @since 2019-11-20
 */
@Configuration
public class ConverterConfig {

    @Autowired
    private RequestMappingHandlerAdapter handlerAdapter;

    /**
     * 增加字符串转日期的功能
     */
    @PostConstruct
    public void initEditableValidation() {
        WebBindingInitializer webBindingInitializer = handlerAdapter.getWebBindingInitializer();
        if (!(webBindingInitializer instanceof ConfigurableWebBindingInitializer)) {
            return;
        }
        ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) webBindingInitializer;
        if (initializer.getConversionService() == null) {
            return;
        }
        ConversionService conversionService = initializer.getConversionService();
        if (!(conversionService instanceof GenericConversionService)) {
            return;
        }
        GenericConversionService service = (GenericConversionService) conversionService;
        service.addConverter(new LocalDateTimeConverter());
        service.addConverter(new LocalDateConverter());
    }
}
